package ch9;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.File;
import java.io.FileWriter;
import java.util.*;

public class XMLDelete {
	public static void main(String[] args) throws Exception {
		SAXReader reader = new SAXReader();
		Document doc = reader.read(new File("src/ch9/clothes.xml"));
		Scanner in = new Scanner(System.in);
		// genju ping pai chazhao shangpin
		System.out.println("请输入要删除的品牌：");
		String brand = in.next();
		List<Element> list = doc.selectNodes("/clothes/cloth[brand='" + brand + "']");
		if (list.size() == 0) {
			System.out.println("没有找到");
			return;
		}
		for (Element e : list) {
			// e就是要删除的对象
			e.getParent().remove(e);
		}
		// >>>写入文件
		OutputFormat format = OutputFormat.createPrettyPrint();
		format.setEncoding("utf-8");
		XMLWriter xm = new XMLWriter(new FileWriter("src/ch9/clothes.xml"), format);
		xm.write(doc);
		xm.close();
		System.out.println("修改成功");
	}
}
